//
//  SearchViewController.m
//  JJHW_coreData
//
//  Created by lizhenqiang on 16/4/9.
//  Copyright © 2016年 HFKJ_LZQ. All rights reserved.
//

#import "SearchViewController.h"
#import "CustomSearchHeadView.h"
#import "SearchViewCell.h"
#import "SearchObj.h"
#import "ZiXunDetailViewController.h"
#define ksearchPageSize 30

@interface SearchViewController ()<UIScrollViewDelegate>

@property(strong,nonatomic)CustomSearchHeadView *headView;
@property(assign,nonatomic)KcontentType contentType;
//@property(nonatomic, strong)NSMutableArray *arrayResults;  //搜索结果
@end

@implementation SearchViewController

- (void)viewDidLoad {
    self.isSupportSingleTapHideKeyboard = YES;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self.tableView.mj_header endRefreshing];
//    [self.tableView.mj_footer endRefreshing];
    self.navLabel.enabled = YES;
//    self.navLabel.clearsOnBeginEditing = YES;
    
    NavBarItem *rightItem = [[NavBarItem alloc] init];
    rightItem.type = NavBarItemTypeOnlyStr;
    rightItem.title_normal = @"  取消";
    rightItem.title_selected = @"  取消";
    [self setRightNavItemWith:rightItem];
    [self.view addSubview:_headView];
    self.tableView.frame = CGRectMake(0, 64, DeviceWidth, DeviceHeight-64);
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchViewCell" bundle:nil] forCellReuseIdentifier:@"SearchViewCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self setNavBarTitleView];
    [self.navLabel addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventEditingChanged];
    // Do any additional setup after loading the view from its nib.
//    if (![NSString isEmpty:self.navLabel.text]) {
//        [self getSearchNewsListRequest:self.navLabel.text];
//    }
    [self addRefreshHeaderAndFooterView:self.tableView];
}

-(void)setNavBarTitleView
{
    self.titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 7, DeviceWidth-100, 30)];//100
    self.navLabel = [[UITextField alloc] initWithFrame:CGRectMake(30, 0, DeviceWidth-140, 30)];//145
    self.navLabel.enabled = YES;
    self.navLabel.font = themeFont15;
    self.navLabel.returnKeyType = UIReturnKeySearch;
//    self.navLabel.keyboardType =UIReturnKeySearch;
     self.navLabel.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.backImageview = [[UIImageView alloc] initWithFrame:CGRectMake(10, 7, 15, 15)];
    self.backImageview.image = [UIImage imageNamed:@"icon_searchsmall"];
    [self.titleView addSubview:self.navLabel];
    [self.titleView addSubview:self.backImageview];
    self.navLabel.layer.cornerRadius = 5.0f;
    self.titleView.layer.cornerRadius = 15.0f;
    self.titleView.layer.masksToBounds = YES;
    self.navLabel.layer.masksToBounds = YES;
    self.navigationItem.titleView = self.titleView;
}

-(void)valueChanged:(id)sender
{
    
    if ([NSString isEmpty: self.navLabel.text ]) {
        
    }
    else
    {
        [self loadDataWithCurrentpage:0];
    }
    
}

-(void)loadDataWithCurrentpage:(NSInteger)currentpage
{
    self.currentPage = currentpage;
    [self getSearchNewsListRequest:self.navLabel.text];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.navLabel becomeFirstResponder];
    self.titleView.backgroundColor = [UIColor whiteColor];
    self.backImageview.image = [UIImage imageNamed:@"icon_search_gray"];
    self.navLabel.backgroundColor = [UIColor whiteColor];
    self.navLabel.textColor = kDefaultBlackColor;
    self.navLabel.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入关键词" attributes:@{NSForegroundColorAttributeName: [UIColor grayColor]}];
    self.navLabel.tintColor = [UIColor grayColor];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self.navLabel resignFirstResponder];
}
-(void)rightItemClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma mark - UITableView DataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.pageDataArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:@"SearchViewCell" cacheByIndexPath:indexPath configuration:^(SearchViewCell *cell) {
        [self configureCell:cell atIndexPath:indexPath];
    }];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // in subClass
    SearchViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchViewCell"];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
//    cell.fd_enforceFrameLayout = YES ;
    SearchViewCell *dataCell = (SearchViewCell *)cell;
    SearchObj *obj = self.pageDataArr[indexPath.row];
    [dataCell setCellData:obj];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SearchObj *obj = self.pageDataArr[indexPath.row];
    ZiXunDetailViewController *newsDetail =[[ZiXunDetailViewController alloc] init];
    newsDetail.newsId =obj.internalBaseClassIdentifier;
    [self.navigationController pushViewController:newsDetail animated:YES];
}

#pragma mark textfield 代理区

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self getSearchNewsListRequest:textField.text];
    [self.view endEditing:YES];
    return YES;
}

-(void)getSearchNewsListRequest:(NSString *)searchText
{//资讯列表
    /*
     count:20,一次请求多少条记录
     offset:1,从第几条记录开始请求,偏移量
     pCategoryId:xxx,一级分类id
     categoryId:xxx二级分类id
     countryId:xxx国家id
     districtId:xxx城市id
     */
    NSInteger offset = self.currentPage * ksearchPageSize;
    NSInteger count = ksearchPageSize;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:searchText,@"keyword",NSStringFromIntL(count),@"count",NSStringFromIntL(offset),@"offset",@"",@"countryId",@"",@"districtId",@"",@"pCategoryId",@"",@"categoryId", nil];
    
    [[CDAPIManager sharedManager] request_newsSearch_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if (isSuccess) {
            
//            [self.pageDataArr removeAllObjects];
            NSDictionary *mydic = [data objectForKey:@"data"];
            NSArray *array = [mydic objectForKey:@"list"];
            if (array.count>0) {
                if (self.currentPage == 0) {
                    [self.pageDataArr removeAllObjects];
                }
            }
            for (NSDictionary *dic in array) {
                SearchObj *obj = [[SearchObj alloc] initWithDictionary:dic];
                [self.pageDataArr addObject:obj];
                
            }
            NSInteger total = [[mydic objectForKey:@"total"] integerValue];
            NSInteger totalPage;
            if (total % ksearchPageSize == 0) {
                totalPage = total/ksearchPageSize;
            }
            else
            {
                totalPage = total/ksearchPageSize + 1;
            }
            [self setTotalPages:totalPage];
            [self.tableView reloadData];
            [self endRefreshControlLoading];
            [self.view endEditing:YES];
        }
    }];
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.navLabel resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
